import axios from 'axios'
import Vue from 'vue'
import router from '../router'
import {
  MessageBox,
  Message
} from 'element-ui'

   
// 创建一个axios实例
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // 当跨域请求时发送cookie
  timeout: 5000 // request timeout
})
/* 记录当前请求是否完成，默认是关闭禁用状态 */
window.currentResq = {
  done: true,
  config: {},
};
console.log(window.currentResq );
Vue.prototype.$loading1 = window.currentResq.done;
// 请求拦截器
service.interceptors.request.use(
  config => {

    window.currentResq = {
      done: false,
      config,
    };
    Vue.prototype.$loading1 = window.currentResq.done;
    console.log(config);
    localStorage.token && (config.headers["token"] = localStorage.token);
    return config
  },
  error => {
    // 错误请求返回
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(response => {
    response.headers.token && (localStorage.token = response.headers.token);
    const { config } = window.currentResq;
    const { url, method, data } = response.config;
    if (config.url === url && config.method === method && config.data === data) {
        window.currentResq.done = true;
    }
    Vue.prototype.$loading1 = window.currentResq.done;
   
    // 后端返回的错误信息，统一提示
    if (response.data.code && response.data.code != '00000') {
      Message.error(response.data.message);
    }
    return response;
  },
  error => {
   
    const { config } = window.currentResq;
    const { url, method, data } = error.response.config;
    if (config.url === url && config.method === method && config.data === data) {
        window.currentResq.done = true;
    }

    //根据不同的状态码，处理
    if (error.response.status == 403) {
      if (error.response.data.code == 'A0302') {
   
          MessageBox({
            title: '提示',
            message: error.response.data.message,
            confirmButtonText: '确定',
            callback: action => {
              sessionStorage.clear();
              localStorage.removeItem('token')
              localStorage.removeItem('buttenpermissions')
              localStorage.removeItem('roles')
              localStorage.removeItem('loginName')
              router.push("/login");
              window.location.reload()
            }
          });
        
      }
    } else if (error.response.status != 404) {
      if (error.response.data.code == 'A0301') {
        router.push("/403");
      } else {
        //全局封装请求 如果报错 就直接这里提示
        Message.error(error.response.data.message);
      }
    } else {
      Message.error(error.response.data.message);
    }
    return Promise.reject(error)
  }
)

export default service
